const db = require("../models");

class OrdersPayRepository {
  // 添加新的订单
  async addNewOrder(orderData) {
    try {
      const newOrder = await db.OrdersPay.create(orderData);
      return newOrder;
    } catch (error) {
      console.log("充值订单出错: ");
      console.log(error);
      return false;
    }
  }

  // 根据 ID 删除订单
  async deleteOrderById(id) {
    const order = await db.OrdersPay.findOne({ where: { id } });
    return order
      ? (await db.OrdersPay.destroy({ where: { id } }), true)
      : false;
  }

  // 根据 user_id 查询订单
  async getOrdersByUserId(userId) {
    return await db.OrdersPay.findAll({ where: { user_id: userId } });
  }

  // 获取所有订单
  async getAllOrders() {
    return await db.OrdersPay.findAll();
  }

  // 获取最新的5条订单
  async getLatestOrders(userId) {
    try {
      // 查询最新的5条订单数据
      const latestOrders = await db.OrdersPay.findAll({
        where: { user_id: userId },
        limit: 5, // 限制结果为5条
        order: [["createdAt", "DESC"]], // 按创建时间降序排列
      })
      if (!latestOrders || latestOrders.length === 0) {
        return [];
      }
      return latestOrders
    } catch (error) {
      console.error("获取最新订单时发生错误：", error);
      throw error
    }
  }
}

module.exports = new OrdersPayRepository();
